﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Happy.Web.Mvc.Newtonsoft
{
    /// <summary>
    /// Guid 转换器。
    /// </summary>
    public sealed class GuidConverter : JsonConverter
    {
        /// <inheritdoc />
        public override bool CanConvert(Type objectType)
        {
            return typeof(Guid) == objectType;
        }

        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return Guid.Empty;
            }

            var strGuid = reader.Value as string;
            if (string.IsNullOrEmpty(strGuid))
            {
                return Guid.Empty;
            }

            Guid result;
            if (Guid.TryParse(strGuid, out result))
            {
                return result;
            }

            return Guid.Empty;
        }

        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue((Guid)value);
        }
    }
}
